#pragma once

#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <functional>
#include <cstring>
#include <iostream>
#include <unistd.h>
#include "err.hpp"

using func_t = std::function<std::string(const std::string&)>;

const int backlog = 32;

class ns_server;

class ThreadData
{
public:
    ThreadData(int sock,std::string serverIp,uint16_t serverPort,ns_server* server)
        :_sock(sock)
        ,_serverIp(serverIp)
        ,_serverPort(serverPort)
        ,_server(server)
    {}
public:
    int _sock;
    std::string _serverIp;
    uint16_t _serverPort;
    ns_server* _server;
};

class ns_server
{
public:
    ns_server(uint16_t port,func_t func)
        :_port(port)
        ,_func(func)
    {}

    void init()
    {
        _listensock = socket(AF_INET,SOCK_STREAM,0);
        if(_listensock < 0)
        {
            std::cout << "creat socket fail" << std::endl;
            exit(SOCK_ERR);
        }
        std::cout << "creat socket success" << std::endl;

        struct sockaddr_in local;
        memset(&local,0,sizeof(local));
        local.sin_family = AF_INET;
        local.sin_addr.s_addr = INADDR_ANY;
        local.sin_port = htons(_port);
        if(bind(_listensock,(struct sockaddr*)&local,sizeof(local)) < 0)
        {
            std::cout << "bind socket fail" << std::endl;
            exit(BIND_ERR);
        }
        std::cout << "bind socket success" << std::endl;

        if(listen(_listensock,backlog) < 0)
        {
            std::cout << "listen fail" << std::endl;
            exit(LISTEN_ERR);
        }
        std::cout << "listen success" << std::endl;
    }

    void start()
    {
        struct sockaddr_in local;
        while(true)
        {
            memset(&local,0,sizeof(local));
            socklen_t len = sizeof(local);
            int sock = accept(_listensock,(struct sockaddr*)&local,&len);
            if(sock < 0)
            {
                std::cout << "accept fail" << std::endl;
            }
            std::string clientIp = inet_ntoa(local.sin_addr);
            uint16_t clientPort = ntohs(local.sin_port);
            std::cout << clientIp << "-" << clientPort <<" accept success" << std::endl;

            pthread_t tid;
            ThreadData* data = new ThreadData(sock,clientIp,clientPort,this);
            pthread_create(&tid,nullptr,ThreadRoutine,data);//这里不能回收sock，因为同一进程的线程共享文件描述符表
        }
    }

    static void* ThreadRoutine(void* argc)
    {
        pthread_detach(pthread_self());//线程分离，这样就不用回收了
        ThreadData* data = static_cast<ThreadData*>(argc);
        data->_server->service(data->_sock,data->_serverIp,data->_serverPort);
        delete data;
        return nullptr;
    }

    void service(int sock,std::string clientIp,uint16_t clientPort)
    {
        char buffer[1024];
        while(true)
        {
            int n = read(sock,buffer,sizeof(buffer) - 1);
            if(n < 0)
            {
                std::cout << "read fail" << std::endl;
                exit(READ_ERR);
            }
            else if(n == 0)
            {
                std::cout << clientIp << "-" << clientPort <<" exit" << std::endl;
                close(sock);
                break;//线程，不能用exit，exit是终止进程，那么所有的线程都会退出，这里只要某个线程退出
            }
            else
            {
                buffer[n] = '\0';
                std::string result = _func(buffer); 
                n = write(sock,result.c_str(),result.size());
                if(n < 0)
                {
                    std::cout << "write fail" << std::endl;
                    exit(WRITE_ERR);
                }
            }

        }
    }

    ~ns_server()
    {}
private:
    int _listensock;
    uint16_t _port;
    func_t _func;
};
